package cn.doitedu.javase.thread;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

public class _02_线程同步方式2 {

    static Integer count = 0;
    // 可重入锁
    static ReentrantLock reentrantLock = new ReentrantLock();


    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Adder1());
        Thread t2 = new Thread(new Adder2());

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count);
    }


    static class Adder1 implements Runnable {

        Random random = new Random();

        @Override
        public void run() {
            System.out.println(random.nextInt(100));

            reentrantLock.lock();  // 锁住

            for (int i = 0; i < 5000; i++) {
                count++;
            }
            reentrantLock.unlock(); // 释放锁

        }
    }

    static class Adder2 implements Runnable {

        Random random = new Random();

        @Override
        public void run() {
            System.out.println(random.nextInt(100));

            int i = 0;
            reentrantLock.lock();
            while (i < 5000) {
                count += 2;
                i++;
            }
            reentrantLock.unlock();


        }
    }


}
